package com.myblog.handler.security;

import com.alibaba.fastjson.JSON;
import com.myblog.Utils.WebUtils;
import com.myblog.domain.GlobalResponse;
import com.myblog.domain.entity.enums.GlobalResponseEnum;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();
        GlobalResponse result = null;

        //响应给前端
        //BadCredentialsException用户名和密码错误
        //InsufficientAuthenticationException
        if(e instanceof BadCredentialsException){
            result=GlobalResponse.error(GlobalResponseEnum.LOGIN_ERROR.getCode(),e.getMessage());
        }else if(e instanceof InsufficientAuthenticationException){
            result=GlobalResponse.error(GlobalResponseEnum.NEED_LOGIN);
        }else{
            result=GlobalResponse.error(GlobalResponseEnum.ERROR.getCode(),"认证或授权失败");
        }
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));

    }
}
